package com.wang.jmonkey.ca.api;

import com.wang.jmonkey.ca.handler.code.ValidateCodeHandlerHolder;
import com.wang.jmonkey.ca.model.ValidateCode;
import com.wang.jmonkey.common.constant.ValidateConstant;
import com.wang.jmonkey.common.result.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 验证码服务接口
 * @Author HeJiawang
 * @Date 2021/5/11 9:42
 */
@Slf4j
@RestController
@RequestMapping("/validate")
public class ValidateCodeApi {

    @Autowired
    private ValidateCodeHandlerHolder validateCodeHandlerHolder;

    /**
     * 获取数字图片类型的验证码
     * @param request request
     * @param response response
     * @return 验证码
     */
    @GetMapping("/getImageCode")
    public HttpResult<ValidateCode> getValidateCode(HttpServletRequest request , HttpServletResponse response) {
        HttpResult<ValidateCode> result = new HttpResult<>();

        try {
            ValidateCode validateCode = validateCodeHandlerHolder.findValidateCodeProcessor(ValidateConstant.ValidateCodeType.ImageValidateCodeHandler)
                    .build(ValidateConstant.ValidateCodeType.ImageValidateCodeHandler, request, response)
                    .refresh();

            result.setData(validateCode);
        } catch (Exception e) {
            log.error(this.getClass().getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(), e);

            result.error("获取验证码失败");
        }

        return result;
    }
}
